using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DragonAwakening.Core.World
{
    /// <summary>
    /// Map data processor.
    /// </summary>
    public class WorldMapSizeProcessor : WorldDataProcessor
    {
        /// <summary>
        /// Creates the processor.
        /// </summary>
        public WorldMapSizeProcessor(IWorldDataProcessor next, IWorld world)
            : base(next, world)
        { 
        }

        /// <summary>
        /// Process the data.
        /// </summary>
        public override void Process(string data, int index)
        {
            string widthChunk, heightChunk;
            int nextIndex = this.TryReadDataChunk(data, index, out widthChunk);
            if (nextIndex == -1)
            {
                // [LOG] Error: Map width isn't defined.
                return;
            }

            nextIndex = this.TryReadDataChunk(data, nextIndex, out heightChunk);
            if (nextIndex == -1)
            {
                // [LOG] Error: Map height isn't defined.
            }

            int width = 0;
            int height = 0;

            bool isDataValid = !string.IsNullOrWhiteSpace(widthChunk) && !string.IsNullOrWhiteSpace(heightChunk);
            bool areChunksParsed = isDataValid && int.TryParse(widthChunk, out width) && int.TryParse(heightChunk, out height);
            bool areDimentionsValid = areChunksParsed && height > 0 && width > 0;

            if (areDimentionsValid)
            {
                this.world.CreateWorld(width, height);
                this.InvokeNextProcessor(data, nextIndex);
            }
            else
            {
                // [LOG] Error: Map dimentions are invalid or zero.
            }
        }
    }
}
